<?php
//Set up the system
require('config.include.php');
//Auth stuff
require('auth.include.php');
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Manage Posts</title>
<link rel="stylesheet" href="admin.css" />
<script type="text/javascript" src="editor.js"></script>
</head>

<body>
<div id="wrapper">
	<div id="header">
    	<?php echo('<a href="../" class="breadcrumb">'.SITE_TITLE.'</a> &raquo; <a href="dashboard.php" class="breadcrumb">Dashboard</a> &raquo; <a href="manageposts.php" class="breadcrumb">Manage Posts</a>'); ?>
    </div>
    <div id="sidebar">
<?php
	require('nav.include.php');
?>
    </div>
    <div id="content">
        <div class="contentblock">
				<h2>Edit A Post</h2>
<?php
	if(!isset($_REQUEST['p'])) {
		echo('<h3>Select Post To Edit</h3>');
		$posts=fetch::sortSelection($_p->tb_posts->select('true',array('title','author','timestamp','is_published')),'timestamp',SORT_DESC);
		if(count($posts)>0) {
			//Count pages
			$total_posts=count($posts);
			$pages=$total_posts/POSTS_PER_LIST;
			//If we can't divide cleanly, add one to the pages to cover the missing remainder because php will round down
			if($total_posts%POSTS_PER_LIST!=0)
				$pages=floor($pages)+1;
			//Decide what page is showing
			$p=isset($_REQUEST['postp'])?$_REQUEST['postp']:0;
			echo('<div class="pagination">');
			//Pagination
			if($pages!=1&&$pages!=0) {
				$i=$p-PREVIOUS_PAGES;
				if($i<0)
					$i=0;
				if($p>0)
					echo('<a class="first" href="manageposts.php?postp=0">&laquo; First</a> ');
				if($p>1)
					echo('<a class="previous" href="manageposts.php?postp='.($p-1).'">Previous</a> ');
				for(;$i<$p;$i++)
					echo('<a class="last5" href="manageposts.php?postp='.$i.'">'.$i.'</a> ');
				echo('<a class="current"a href="manageposts.php?postp='.$p.'">'.$p.'</a> ');
				$i=$p+NEXT_PAGES+1;
				if($i>$pages)
					$i=$pages;
				for($y=$p+1;$y<$i;$y++)
					echo('<a class="next5" href="manageposts.php?postp='.$y.'">'.$y.'</a> ');
				if($p<$pages-2)
					echo('<a class="next" href="manageposts.php?postp='.($p+1).'">Next</a> ');
				if($p<$pages-1)
					echo('<a class="last" href="manageposts.php?postp='.($pages-1).'">Last ('.($pages-1).') &raquo;</a>');
			}
			echo('</div>');
			//Show posts on that page
			$startat=$p*POSTS_PER_LIST;
			$i=0;
			$y=POSTS_PER_LIST;
			echo('<ul>');
			foreach($posts as $pid => $d) {
				if($i==$startat) {
					if($y>0) {
						echo('<li><strong>'.$d['title'].'</strong> by '.$_p->tb_users->getFieldValue($d['author'],'username').' on '.date('j<\s\up>S</\s\up> M y',$d['timestamp']).' ('.($d['is_published']===true?'Published':'Draft').')<br />
						<a href="manageposts.php?p='.$pid.'&amp;edit">Edit</a> | 
						<a href="manageposts.php?p='.$pid.'&amp;delete">Delete</a></li>');
						$y--;
					}
					else {
						break;
					}
				}
				else {
					$i++;
				}
			}
			echo('</ul>');
		}
		else {
			echo('There are no posts yet.');
		}
	}
	//If in edit mode
	elseif(isset($_REQUEST['edit'])) {
		$printform=true;
		$pid=isset($_GET['p'])?$_GET['p']:$_POST['p'];
		
		//Get existing categories if not loaded
		if(!is_array($_POST['categories'])) 
			$_POST['categories']=$_p->tb_posts->getFieldValue($pid,'categories');
		
		//Fix categories if empty
		if(count($_POST['categories'])==0)
			$_POST['categories']=array(0);
		
		//noedits tells us if new data could have been recieved
		if(isset($_POST['publish'])||isset($_POST['draft'])||isset($_POST['preview'])||isset($_POST['attach'])||isset($_POST['attachsearch']))
			$noedits=false;
		else
			$noedits=true;
		//Get data from the database or from the user's submission?
		if(!$noedits) {
			$comments=false;
			if($_POST['comments']==1)
				$comments=true;
			$postcontent=fetch::unescapePostVar($_POST['postcontent']);
			$posttitle=fetch::unescapePostVar($_POST['posttitle']);
		}
		else {
			$comments=$_p->tb_posts->getFieldValue($pid,'comments');
			$postcontent=$_p->tb_posts->getFieldValue($pid,'content');
			$posttitle=$_p->tb_posts->getFieldValue($pid,'title');
		}
		//Do the right thing
		if(isset($_POST['posttitle'])) {
			//Fix post data
			if($_POST['posttitle']==='') {
				echo('<h3>Error</h3>
				Please enter a title.<br />');
			}
			else {
				//Publishing or drafting or attaching
				if(isset($_POST['attach'])||isset($_POST['attachsearch'])) {
					//Attachment system uploads
					if(isset($_POST['attach'])) {
						echo('<br />Attaching...');
						//Add and check result
						if(($attachedFile=$_p->attach(basename($_FILES['file_upload']['name']),$_FILES['file_upload']['tmp_name'],'../'.UPLOAD_PATH))!==false)
							echo('<br />Attachment "'.$attachedFile.'" added.');
						else
							echo('<br />Attachment failed to be added.');
					}
				}
				elseif(isset($_POST['publish'])||isset($_POST['draft'])) {
					echo('
					<h3>Post Saved</h3>
					<a href="manageposts.php?p='.$pid.'&amp;edit">Continue editing</a>');
					if(isset($_POST['publish'])) {
						$_p->edit_post($pid,$posttitle,$postcontent,$comments,true,$_POST['categories']);
						
						//Rebuild the rss feed
						$rssFile='../'.RSS_PATH;
						$xml=$_p->rebuildRSS();
						$rssHandle=fopen($rssFile,'w+');
						fwrite($rssHandle,$xml);
						fclose($rssHandle);
						echo(' | <a href="../index.php?post='.$pid.'">View Post</a>');
					}
					else
						$_p->edit_post($pid,$posttitle,$postcontent,$comments,false,$_POST['categories']);
					$printform=false;
				}
				//Preview
				else {
					echo('
					<h3>Previewing Post</h3>'.
					$_p->parsePost($postcontent,USE_GESHI_POSTS));
				}
			}
		}
		
		if($printform) {
		echo('
			<form enctype="multipart/form-data" action="manageposts.php" method="post">
				<h3>Title</h3>
				<input type="text" class="full" name="posttitle" value="'.$posttitle.'"/>
				<h3>Content</h3>
				<div class="toolbar">
				<a href="#" title="Bold" onclick="addtag(\'postcontent\', \'B\')"><b>B</b></a>
				<a href="#" title="Italics" onclick="addtag(\'postcontent\', \'I\')"><i>I</i></a>
				<a href="#" title="Underline" onclick="addtag(\'postcontent\', \'U\')"><u>U</u></a>
				<a href="#" title="Strikethrough" onclick="addtag(\'postcontent\', \'S\')"><s>S</s></a>
				<a href="#" title="Superscript" onclick="addtag(\'postcontent\', \'SUP\')">x<sup>2</sup></a>
				<a href="#" title="Subscript" onclick="addtag(\'postcontent\', \'SUB\')">x<sub>2</sub></a>
				<a href="#" class="deform" title="Code" onclick="addtag(\'postcontent\', \'CODE\')">code</a>
				<a href="#" class="deform" title="Create A Link" onclick="addurl(\'postcontent\')">url</a>
				<a href="#" class="deform" title="Insert an Image" onclick="addtag(\'postcontent\', \'IMG\')">img</a>
				<a href="#" class="deform" title="Add ReadMore Tag" onclick="addtext(\'postcontent\', \'[readmore]\')">readmore</a>
				<a href="#" class="deform" title="Add Link to a Post" onclick="linkpost(\'postcontent\')">+post</a>
				<a href="#" class="deform" title="Add Link to a Page" onclick="linkpage(\'postcontent\')">+page</a>
				</div>
				<textarea class="full" rows="30" cols="60" name="postcontent" id="postcontent">'.$postcontent.'</textarea>
				<h3>Add Attachments</h3>');
				//Attachment system searching
				if(isset($_POST['attachsearch'])) {
					$searchResults=$_p->search_attachments($_POST['attachment_search_text'],'../'.UPLOAD_PATH);
					if($searchResults!==false) {
						if(count($searchResults)>0) {
							foreach($searchResults as $result) {
								echo('<strong>'.$result.'</strong> &raquo; Add a <a href="javascript:addtext(\'postcontent\',\'[attach='.$result.']'.$result.'[/attach]\')">download link</a>');
								
								//If is image, then show the embed link
								$ext=substr(strrchr($result,'.'),1);
								if($ext=='jpg'||$ext=='gif'||$ext=='bmp'||$ext=='png')
									echo(' or <a href="javascript:addtext(\'postcontent\',\'[img]download.php?attach='.$result.'[/img]\')">embed as image</a>');
								
								echo(' into this post<br />');
							}
						}
						else {
							echo('No results were returned, try broadening your search');
						}
					}
					else {
						echo('There was a problem getting the list of attachments; perhaps you haven\'t uploaded any?');
					}
				}
		echo('
				<input type="text" id="attachment_search_text" name="attachment_search_text" value="Enter filename to search for..." onfocus="javascript:clearsearch();" />
				<br /><br />
				<input type="submit" name="attachsearch" value="Search" />
				<h3>Upload Attachments</h3>
				<input type="file" name="file_upload" />
				<input type="hidden" name="MAX_FILE_SIZE" value="'.MAX_UPLOAD_BYTES.'" /><br />
				Maximum upload size: '.MAX_UPLOAD_BYTES.' bytes<br />
				<br />
				<input type="submit" name="attach" value="Upload" />
				<h3>Allow Comments</h3>
				<input type="radio" name="comments" '.($comments?'checked="checked"':'').' value="1" /> Yes<br />
				<input type="radio" name="comments" '.(!$comments?'checked="checked"':'').' value="0" /> No
				<h3>Categories</h3>');
			//Category selection
			$categories=$_p->get_categories();
			if(count($categories)==0)
				echo('No categories available');
			foreach($categories as $catID=>$catInfo) {
				echo('<input type="checkbox" name="categories[]" value="'.$catID.'"'.(array_search($catID,$_POST['categories'])!==false?' checked="checked"':'').' /> '.$catInfo['name'].'<br />');
			}
			echo('
				<h3>Action</h3>
				<input type="submit" name="publish" value="Publish" />
				<input type="submit" name="draft" value="Save as draft" />
				<input type="submit" name="preview" value="Preview" />
				<input type="hidden" name="edit" />
				<input type="hidden" name="p" value="'.$pid.'" />
			</form>
		');
		}
	}
	elseif(isset($_REQUEST['delete'])) {
		if(!isset($_REQUEST['confirm'])) {
			echo('<h3>Deleting Post</h3>
			You are about to delete the post "'.htmlentities($_p->tb_posts->getFieldValue($_REQUEST['p'],'title'),ENT_QUOTES,"UTF-8").'"<br />
			<a href="manageposts.php?p='.$_REQUEST['p'].'&amp;delete&amp;confirm">Confirm</a> | 
			<a href="manageposts.php">Cancel</a>');
		}
		else {
			echo('<h3>Deleted Post</h3>
			<a href="manageposts.php">Return</a>');
			$_p->delete_post($_REQUEST['p']);
			$_p->rebuildRSS();
		}
	}
	else {
		echo('<h3>Error</h3>
		Unknown action requested');
	}
?>
		</div>
    </div>
    <div id="footer">
    </div>
</div>
</body>
</html>